package com.example.demo.test;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 编写一个程序，开启 3 个线程，这三个线程的 ID 分别为 A、B、C，每个线程将自己的 ID 在屏幕上打印 10
 * 遍，要求输出的结果必须按顺序显示。
 * 如：ABCABCABC…… 依次递归。
 */
public class test1 {
    public static void main(String[] args) {
        order order = new order();
        new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 10; i++) {
                    order.lockA();
                }
            }
        }, "A").start();

        new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 10; i++) {
                    order.lockB();

                }
            }
        }, "B").start();

        new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 10; i++) {
                    order.lockC();
                }
            }
        }, "C").start();


    }
}

class order {
    private int num = 1;

    Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    public void lockA() {
        lock.lock();
        try {
            if (num != 1) {
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName());
            num = 2;
            condition2.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void lockB() {
        lock.lock();
        try {
            if (num != 2) {
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName());
            num = 3;
            condition3.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void lockC() {
        lock.lock();
        try {
            if (num != 3) {
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName());
            num = 1;
            condition1.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}